<template>
  <div>
    <el-card style="margin-bottom: 20px">
      <span style="margin-right: 8px">主题查询</span>
      <el-input
        v-model="title"
        placeholder="请输入主题关键字"
        clearable
        style="width: 200px; margin-right: 8px"
      ></el-input
      ><el-button type="primary" @click="search">搜索</el-button>
    </el-card>
    <!-- 按钮 -->
    <el-button type="primary" icon="el-icon-plus" @click="addArticle"
      >添加</el-button
    >
    <!-- 表格组件 -->
    <el-table border style="width: 100%; margin-top: 8px" :data="articleList">
      <el-table-column type="index" label="序号" width="90px" align="center">
      </el-table-column>
      <el-table-column prop="title" label="主题" width="90px" align="center">
      </el-table-column>
      <el-table-column prop="imgList" label="轮播图片" width="width">
        <template slot-scope="{ row }">
          <el-image
            style="width: 100px; height: 100px"
            :src="row.images[0]"
            :preview-src-list="row.images"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="using"
        label="正在使用"
        width="90px"
        align="center"
      >
        <template slot-scope="{ row }">
          <el-button
            v-if="row.isUsing == 0"
            type="info"
            icon="el-icon-minus"
            size="mini"
            @click="setUsing(row)"
          ></el-button>
          <el-button
            v-else
            type="primary"
            icon="el-icon-check"
            size="mini"
          ></el-button>
        </template>
      </el-table-column>

      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{ row, $index }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            @click="updateArticle(row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteArticle(row, $index)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 对话框 -->
    <el-dialog
      :title="articleInfo.id ? '修改轮播图' : '添加轮播图'"
      :visible.sync="dialogFormVisible"
    >
      <el-form style="width: 80%" :model="articleInfo" ref="ruleForm">
        <el-form-item label="主题" label-width="60px">
          <el-input autocomplete="off" v-model="articleInfo.title"></el-input>
        </el-form-item>
        <el-form-item label="轮播图" label-width="60px">
          <el-upload
            action="/article"
            list-type="picture-card"
            name="file"
            :multiple="true"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :auto-upload="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :show-file-list="true"
            :on-change="changeImage"
            :file-list="fileList"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitArticleForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-pagination
      style="margin-top: 30px; text-align: center"
      :current-page="page"
      :page-sizes="[3, 5, 10]"
      :page-size="limit"
      layout=" prev, pager, next, jumper,->,total, sizes"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="getArticleListSelectPage"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  name: "tradeMark",
  data() {
    return {
      page: 1,
      limit: 3,
      total: 0,
      list: [],
      //控制对话框的显示与隐藏
      dialogFormVisible: false,
      //表单数据
      articleInfo: {
        title: "",
      },
      articleList: [], // 所有轮播图数据
      title: "", //input框主题
      type: 0, //0:添加轮播图,1:修改轮播图
      fileList: [],
    };
  },
  created() {
    this.getPageList();
  },
  methods: {
    //分页获取轮播图数据
    async getPageList() {
      const { page, limit } = this;
      let result = await this.$API.article.reqGetArticleByPage(page, limit);
      //分别展示数据总条数与列表展示的数据
      if (result.code == "200") {
        this.total = result.data.total;
        this.articleList = result.data.records;
        this.formatImageUrl();
      }
    },

    //搜索按钮事件
    search() {
      if (this.title !== "") {
        this.searchPageByTitle();
      } else {
        this.getPageList();
      }
    },

    //根据主题查询
    async searchByTitle() {
      let res = await this.$API.carousel.reqGetByTitle(this.title);
      if (res.code == "200") {
        this.articleList = res.data;
      }
    },

    //根据主题获取数据（分页）
    async searchPageByTitle() {
      let res = await this.$API.article.reqGetPageByTitle(
        this.page,
        this.limit,
        this.title
      );
      if (res.code == "200") {
        this.articleList = res.data.records;
        this.total = res.data.total;
        this.formatImageUrl();
      }
    },

    //添加按钮事件
    addArticle() {
      this.dialogFormVisible = true;
      this.type = 0;
    },

    //设置在用轮播图
    async setUsing(row) {
      let res = await this.$API.article.reqsetUsing(row.id);
      if (res.code == "200") {
        this.getPageList();
        this.$message({
          message: "设置成功",
          type: "success",
        });
      }
    },

    //修改文章按钮事件
    updateArticle(row) {
      row.images.map((itme) => {
        this.fileList.push({ url: itme });
      });
      this.type = 1;
      Object.assign(this.articleInfo, row);
      this.dialogFormVisible = true;
    },

    //提交添加或修改分类
    async submitArticleForm() {
      let formData = new FormData();
      this.fileList.forEach((item) => {
        if (item.raw) {
          formData.append("file", item.raw);
        }
      });
      Object.entries(this.articleInfo).map(([key, value]) => {
        if (key == "images") {
          value.forEach((item) => {
            if (!(typeof item == "string")) {
              formData.append("images", item.url);
            } else {
              formData.append("images", item);
            }
          });
          return;
        }
        formData.append(key, value);
      });
      if (this.type === 0) {
        let res = await this.$API.article.reqAddArticle(formData);
        if (res.code === "200") {
          this.$message({ message: "添加成功", type: "success" });
          this.getPageList();
          this.dialogFormVisible = false;
          this.articleInfo = {};
          this.fileList = [];
        } else {
          this.$message({ message: "添加失败", type: "error" });
        }
      } else {
        let res = await this.$API.article.reqUpdateArticle(formData);
        if (res.code === "200") {
          this.$message({ message: "修改成功", type: "success" });
          this.getPageList();
          this.dialogFormVisible = false;
          this.articleInfo = {};
          this.fileList = [];
        } else {
          this.$message({ message: "修改失败", type: "success" });
        }
      }
    },

    //删除文章
    deleteArticle(row, index) {
      this.$confirm(`是否删除${row.title}该主题文章?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await this.$API.article.reqDeleteArticle(row.id);
          if (res.code == "200") {
            this.$message({
              type: "success",
              message: "删除成功",
            });
            this.articleList.splice(index, 1);
            this.getPageList(
              this.articleList.length > 1 ? this.page : this.page - 1
            );
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //分页器选择页码
    getArticleListSelectPage(pages = 1) {
      this.page = pages;
      if (this.title !== "") {
        this.searchPageByTitle();
      } else {
        this.getPageList();
      }
    },

    //切换每页显示数
    handleSizeChange(limits) {
      this.limit = limits;
      this.getArticleListSelectPage();
    },

    //删除图片按钮事件
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.articleInfo.images = fileList;
      // console.log(file, fileList, "+++++++++++++++");
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisibleImg = true;
    },
    //上传或删除图片触发事件
    changeImage(file, fileList) {
      this.fileList = fileList;
    },

    //关闭弹窗
    closeDialog() {
      this.articleInfo = {};
      this.dialogFormVisible = false;
    },

    handleAvatarSuccess(res, file) {
      // this.tradeForm.logoUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === "image/jpeg";
      // const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isJPG) {
      //   this.$message.error("上传头像图片只能是 JPG 格式!");
      // }
      // if (!isLt2M) {
      //   this.$message.error("上传头像图片大小不能超过 2MB!");
      // }
      // return isJPG && isLt2M;
    },

    //格式化图片路径
    formatImageUrl() {
      this.articleList.forEach((item) => {
        if (item.images !== "" && item.images !== null) {
          item.images = item.images
            .replace(/\[|\]/g, "")
            .replace(/\s+/g, "")
            .split(",");
          item.images.forEach((i, index, arr) => {
            arr[index] = `http://localhost:8080/api/img/` + i;
          });
        }
      });
    },
  },
  mounted() {
    // this.getPageList();
  },
};
</script>

<style >
</style>